import { Breadcrumb, Table, Space, Button, TableProps, Tabs, Modal, message } from 'antd';
import React, { FC } from 'react';
import { FormPanel, FormPanelBtnAlign, type FormPanelObject, InputType, Utils } from 'lfun-bg-comp';
import _ from 'lodash';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { PageContainer } from '@/component/page-container';
import { PAGINATIONCONFIG } from '@/constant/page';
import utils, { getPathRoot } from '@/utils';
import { GENDER } from '@/constant/basicOptions';
import { TransactionPageParams, transactionPage, transferinCancel } from '@/service/student/instudent';
import styles from './index.less';
import { searchSchoolOptions } from '@/service/options';
import { APPROVAL_STATUS, AUDIT_STATUS, DIRECTION } from '@/constant';
import { transferRevoked } from '@/service/teacher/transfer';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';

const Groups: FC = () => {
  const navigate = useNavigate();
  const [value, setValue] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(10);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [loading, setLoading] = React.useState(false);
  // const [condition, setCondition] = React.useState<any>({ student_gender: 'male', audit_status: 'needaudit' });
  const [condition, setCondition] = React.useState<any>({});
  const [curFormPanelObject, setCurFormPanelObject] = React.useState<any>();
  const isSchool = Utils.getProps('isSchool');

  const list = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '当前学校',
          name: 'school_id',
          key: 'school_id',
          inputType: InputType.search,
          renderOption: searchSchoolOptions,
          formatSubmitValue: val => {
            if (typeof val === 'object') {
              return val.value;
            }
            return val;
          },
        },
        {
          label: '姓名',
          name: 'student_name',
          key: 'student_name',
          textRange: [0, 20],
        },
        {
          label: '性别',
          name: 'student_gender',
          key: 'student_gender',
          inputType: 'select',
          renderOption: GENDER,
        },
        {
          label: '学籍号码',
          name: 'edu_no',
          key: 'edu_no',
          textRange: [0, 20],
        },
        {
          label: '状态',
          name: 'audit_status',
          key: 'audit_status',
          inputType: 'select',
          renderOption: AUDIT_STATUS,
        },
        {
          label: '申请人',
          name: 'apply_user',
          key: 'apply_user',
          textRange: [0, 20],
        },
        {
          label: '类别',
          name: 'direction',
          key: 'direction',
          inputType: 'select',
          hidden: !isSchool,
          renderOption: DIRECTION,
        },
      ],
    },
  ];

  const searchFunc = async (params, pageIndex, pageSize) => {
    setLoading(true);
    const param: TransactionPageParams = {
      ...params,
    };
    const r = await transactionPage(param, pageIndex, pageSize);
    if (r.success) {
      setValue(r?.data?.items || []);
      // setValue([{}]);
      setTotal(r?.data?.total || 0);
      setPageIndex(pageIndex);
      setPageSize(pageSize);
    } else if (curFormPanelObject) {
      curFormPanelObject.reVaildation(r);
    }
    setLoading(false);
  };

  const handleAgainSubmit = record => {
    if (record.direction === 'in') {
      navigate(`${getPathRoot()}/instudent/checkin`);
    } else {
      navigate(`${getPathRoot()}/instudent/checkout`);
    }
  };

  const columns: TableProps['columns'] = [
    {
      title: '姓名',
      dataIndex: 'student_name',
      key: 'student_name',
      fixed: 'left',
      width: 100,
    },
    {
      title: '学籍号码',
      dataIndex: 'edu_number',
      key: 'edu_number',
      fixed: 'left',
      width: 100,
    },
    {
      title: '性别',
      dataIndex: 'student_gender',
      key: 'student_gender',
      width: 100,
      render(v, record, index) {
        return _.find(GENDER, { value: v })?.label;
      },
    },
    {
      title: '类别',
      dataIndex: 'direction',
      key: 'direction',
      width: 100,
      hidden: !isSchool,
      render(v, record, index) {
        return _.find(DIRECTION, { value: v })?.label;
      },
    },
    {
      title: '当前学校',
      dataIndex: 'school_name',
      key: 'school_name',
      width: 200,
    },
    {
      title: '申请人',
      dataIndex: 'apply_user',
      key: 'apply_user',
      width: 100,
    },
    {
      title: '申请时间',
      dataIndex: 'apply_time',
      key: 'apply_time',
      width: 100,
      render: (text: string) => {
        return dayjs(text).format('YYYY-MM-DD');
      },
    },
    {
      title: '状态',
      dataIndex: 'audit_status',
      key: 'audit_status',
      width: 100,
      render: (text: string) => {
        return _.find(AUDIT_STATUS, { value: text })?.label;
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      fixed: 'right',
      //width: 200,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          <PermissionButton permission="view">
            <Button type="link" onClick={() => handleView(record)}>
              查看
            </Button>
          </PermissionButton>
          <PermissionButton permission="out_view">
            <Button type="link" onClick={() => handleViewTransfer(record)}>
              查看转学信息
            </Button>
          </PermissionButton>
          {isSchool && ['needaudit'].includes(record.audit_status) && (
            <PermissionButton permission="approval">
              <Button type="link" onClick={() => handleAudit(record)}>
                审批
              </Button>
            </PermissionButton>
          )}
          {isSchool && ['refuse'].includes(record.audit_status) && (
            <PermissionButton permission="edit">
              <Button type="link" onClick={() => handleAgainSubmit(record)}>
                再次提交
              </Button>
            </PermissionButton>
          )}
          {isSchool && ['needaudit'].includes(record.audit_status) && (
            <PermissionButton permission="revoke">
              <Button
                type="link"
                onClick={async () => {
                  Modal.confirm({
                    title: '撤回',
                    content: `是否撤回${record.student_name}调出?`,
                    onOk: async () => {
                      const res = await transferinCancel(record.process_instance_id);
                      if (res.success) {
                        message.success('撤回成功');
                      } else message.error(res.message || res.details);
                    },
                  });
                }}
              >
                撤回
              </Button>
            </PermissionButton>
          )}
        </Space>
      ),
    },
  ];

  const handleView = record => {
    navigate(`${getPathRoot()}/instudent/transfer/view/${record.student_id}`, { state: { ...record } });
    console.log('查看', record);
  };
  const handleViewTransfer = record => {
    navigate(`${getPathRoot()}/instudent/transfer/view2/${record.student_id}`, { state: { ...record } });
    console.log('查看转学信息', record);
  };

  const handleAudit = record => {
    navigate(`${getPathRoot()}/instudent/transfer/approve/${record.student_id}`, { state: { ...record } });
    console.log('审批', record);
  };

  React.useEffect(() => {
    searchFunc(condition, 1, pageSize);
  }, []);

  const pageChange = (pageIndex, pageSize) => {
    searchFunc({ ...curFormPanelObject?.getFieldsValue(), ...condition }, pageIndex, pageSize);
    setPageIndex(pageIndex);
    setPageSize(pageSize);
  };
  return (
    <PageContainer header={<Breadcrumb items={[{ title: '转学管理' }]} />}>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        submitBtnText="查询"
        values={condition}
        onLoad={(formPanelObject: FormPanelObject) => {
          setCurFormPanelObject(formPanelObject);
        }}
        onFinish={(formPanelObject: FormPanelObject) => {
          searchFunc({ ...formPanelObject.getFieldsValue(), ...condition }, 1, pageSize);
        }}
        template={list}
      />
      {/* <Tabs
        className={styles.tabs}
        type="card"
        onTabClick={key => {
          if (key === '1') {
            searchFunc({ ...curFormPanelObject.getFieldsValue(), audit_status: 'needaudit' }, 1, pageSize);
            setCondition({ audit_status: 'needaudit' });
          } else if (key === '2') {
            searchFunc(
              { ...curFormPanelObject.getFieldsValue(), apply_user: utils.getUserName() || 'me' },
              1,
              pageSize
            );
            setCondition({ apply_user: utils.getUserName() || 'me' });
          } else if (key === '3') {
            searchFunc({ ...curFormPanelObject.getFieldsValue() }, 1, pageSize);
            setCondition({});
          }
        }}
        items={[
          {
            label: '我发起',
            key: '2',
          },
          {
            label: '待审批',
            key: '1',
          },
        ]}
      /> */}
      <Table
        dataSource={value}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
    </PageContainer>
  );
};

export default Groups;
